<?php
/**
 * Created by PhpStorm.
 * User: ytl003
 * Date: 2018/10/11
 * Time: 下午3:55
 */

namespace app\api\controller;


use app\api\model\SiteModel;
use app\api\service\Back;
use app\api\service\TokenService;
use app\api\validate\SiteIdValidate;
use app\api\validate\SiteSettingValidate;
use app\lib\exception\ErrorException;
use think\Db;
use think\Exception;
use think\facade\Request;

class Site
{
    /**
     * @route('site/setting')
     */
    public function save()
    {
        TokenService::needAdminPermission();
        ($validate = new SiteSettingValidate())->goCheck();
        $data = $validate->getDataByRule(Request::post());
        $data['admin_id'] = TokenService::getCurrentUid();
        if (strpos($data['img_url'], 'http') !== false)
            unset($data['img_url']);
        foreach ($data['table_data']['data'] as $key => $d) {
            $data['table_data']['data'][$key]['answer'] = '';
        }
        Db::startTrans();
        try {
            if ($data['type'] == 'new') {
                unset($data['type']);
                unset($data['id']);
                SiteModel::create($data);
            } else if ($data['type'] == 'edit') {
                unset($data['type']);
                $site = SiteModel::get($data['id']);
                if ($site['admin_id'] != $data['admin_id'])
                    return Back::error('你无此场地权限！');
                unset($data['id']);
                unset($data['admin_id']);
                if (!$site)
                    return Back::error('此场地已被删除');
                $site->save($data);
            } else {
                throw new ErrorException(['msg' => '请传入合法的type']);
            }
            Db::commit();
            return Back::success();
        } catch (Exception $e) {
            Db::rollback();
            throw new ErrorException(['msg' => '程序错误，操作失败']);
        }
    }

    /**
     * @param string $type
     * @param string $admin_id
     * @param string $name
     * @param int $site_id
     * @return array
     * @throws \app\lib\exception\ParameterException
     * @throws \app\lib\exception\PermissionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @route('site/get')
     */
    public function getSite($type = '', $admin_id = '', $name = '', $site_id = 0)
    {
        TokenService::needAllUserPermission();
        (new SiteIdValidate())->goCheck();
        $condition = [];
        if ($type == 'all') {
            return Back::success(SiteModel::all());
        } elseif ($type == 'my') {
            $id = TokenService::getCurrentUid();
            if ($name)
                array_push($condition, [
                    'name', 'like', '%' . $name . '%'
                ]);
            if ($site_id != 0)
                array_push($condition, [
                    'id', '=', $site_id
                ]);
            return Back::success(SiteModel::where('admin_id', $id)->where($condition)->select());
        } else {
            if ($admin_id)
                array_push($condition, [
                    'admin_id', '=', $admin_id
                ]);
            if ($name)
                array_push($condition, [
                    'name', 'like', '%' . $name . '%'
                ]);
            if ($site_id)
                array_push($condition, [
                    'id', '=', $site_id
                ]);
            return Back::success(SiteModel::where($condition)->select());
        }
    }

    /**
     * @param $siteId
     * @return array
     * @throws Exception\DbException
     * @throws \app\lib\exception\ParameterException
     * @route('site/delete')
     */
    public function deleteSite($siteId = '')
    {
        (new SiteIdValidate())->goCheck();
        $site = SiteModel::get($siteId);
        if ($site['admin_id'] != TokenService::getCurrentUid())
            return Back::error('你无此场地权限！');
        $site->delete();
        return Back::success();
    }
}